<template>
  <div class="carbon-credit-page">
    <!-- 筛选条件区域 -->
    <div class="filter-section">
      <el-row :gutter="20" class="filter-row">
        <el-col :span="4">
          <div class="filter-item" style="display: flex; align-items: center">
            <span class="filter-label">核证标准</span>
            <el-select
              v-model="form.certificationCriteria"
              placeholder="全部"
              clearable
              class="filter-select"
              style="flex: 1"
              @change="resetMainPagination"
            >
              <el-option v-for="item in certificationCriteria" :label="item.itemCh" :value="item.itemValue":key="item.id" ></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="filter-item" style="display: flex; align-items: center">
            <span class="filter-label">领域</span>
            <el-select
              v-model="form.fieldCode"
              placeholder="全部"
              clearable
              class="filter-select"
              style="flex: 1"
              @change="resetMainPagination"
            >
              <el-option v-for="item in projectScope" :label="item.itemCh" :value="item.itemValue":key="item.id" ></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="filter-item" style="display: flex; align-items: center">
            <span class="filter-label">行业</span>
            <el-select
              v-model="form.industry"
              placeholder="全部"
              clearable
              class="filter-select"
              style="flex: 1"
              @change="resetMainPagination"
            >
              <el-option v-for="item in industory" :label="item.itemCh" :value="item.itemValue":key="item.id" ></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="filter-item" style="display: flex; align-items: center">
            <span class="filter-label">状态</span>
            <el-select
              v-model="form.statusCode"
              placeholder="全部"
              clearable
              class="filter-select"
              style="flex: 1"
              @change="resetMainPagination"
            >
              <el-option v-for="item in statusCode" :label="item.itemCh" :value="item.itemValue":key="item.id" ></el-option>
            </el-select>
          </div>  
        </el-col>
        <el-col :span="8">
          <div style="display: flex;" class="filter-item2">
            <span style="display: 1;margin-top: 8px; " class="filter-label2">方法学搜索</span>
            <div class="search-container">
              <el-input
                v-model="form.mName"
                placeholder="输入方法学名称"
                clearable
                class="search-input"
                @keyup.enter.native="handleMethodSearch"
              ></el-input>
              <el-button type="success" plain @click="queryMethods">查询</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-button 
        type="success" 
        style="display: flex; width: 100px; margin-top: 20px; justify-content: center; align-items: center;" 
        plain 
        @click="dialogVisible=true"
      >+添加方法学</el-button>
    </div>

    <!-- 表格数据区域 -->
    <div class="table">
      <el-table
        :data="tableData"
        stripe
        @selection-change="handleSelectionChange"
        style="width: 100%"
        v-loading="tableLoading"
      >
        <el-table-column prop="id" label="序号" align="center" width="80"></el-table-column>
        <el-table-column
          prop="methodCode"
          label="方法学编号"
          show-overflow-tooltip
          width="160"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="名称"
          align="left"
          show-overflow-tooltip
          width="240"
        ></el-table-column>
        <el-table-column
          prop="fieldCode"
          label="领域 "
          width="180"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="industryCode"
          label="行业"
          width="220"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="certificationCriteria"
          label="核证标准"
          align="center"
          width="210"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="statusCode"
          label="状态"
          align="center"
          width="100"
          show-overflow-tooltip
        ></el-table-column>
        
        <el-table-column label="操作" width="200" align="center">
          <template v-slot="scope">
            <div class="operation-btns">
              <span 
                class="btn-text view" 
                @click="handleView(scope.row.sourceFileUrl)"
              >查看</span>
              <span class="btn-text modify" @click="handleEdit(scope.row)">编辑</span>
              <span class="btn-text delete" @click="handledelete(scope.row)">删除</span>
              <span v-if="scope.row.statusCode === '未发布' || scope.row.statusCode === '已下线'" 
                class="btn-text offline" @click="handleOnline(scope.row)">发布</span>
              <span v-if="scope.row.statusCode === '已发布'" 
                class="btn-text delete" @click="handleDownline(scope.row)">下线</span>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination" v-if="mainTotal > 0">
        <el-pagination
          background
          @current-change="handleMainPageChange"
          @size-change="handleMainPageSizeChange"
          :current-page="mainPageNum"
          :page-size="mainPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="mainTotal"
          :page-count="mainTotalPages"
          :page-sizes="[5, 10, 15, 20]"
        ></el-pagination>
      </div>
    </div>
    
    <!--创建方法学弹窗-->
    <el-dialog
      title="添加方法学"
      :visible.sync="dialogVisible"
      @close="resetOfflineForm"
      width="50%"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form 
        label-width="120px"
        ref="createFormRef" 
        :model="createForm" 
        :rules="formRules"
        size="medium"
      >
        <el-form-item label="方法学编号" prop="methodCode">
          <el-input v-model="createForm.methodCode" placeholder="请输入方法学编号"></el-input>
        </el-form-item>
        <el-form-item label="方法学字典码" prop="dictCode">
          <el-input v-model="createForm.dictCode" placeholder="请输入方法学字典码"></el-input>
        </el-form-item>
        <el-form-item label="方法学名称" prop="name">
          <el-input  v-model="createForm.name" placeholder="请输入方法学名称"></el-input>
        </el-form-item>
        <el-form-item label="领域" prop="fieldCode">
          <el-select v-model="createForm.fieldCode" placeholder="请选择">
            <el-option
            v-for="item in projectScope"
            :key="item.itemCh"  
            :label="item.itemCh" 
            :value="item.itemValue"
          ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="行业" prop="industryCode">
          <el-select v-model="createForm.industryCode" placeholder="请选择行业">
            <el-option
            v-for="item in industory"
            :key="item.itemCh"  
            :label="item.itemCh" 
            :value="item.itemValue"
          ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="核证标准*" prop="certificationCriteria">
          <el-select v-model="createForm.certificationCriteria" placeholder="请选择核证标准">
            <el-option v-for="item in certificationCriteria" :label="item.itemCh" :value="item.itemValue":key="item.id" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="pdf文档url*" prop="sourceFileUrl">
          <el-input v-model="createForm.sourceFileUrl" placeholder="请输入pdf文档url"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetOfflineForm">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "method",
  data() {
    return {
      // 编辑模式标记（true=编辑，false=新增）
      isEditMode: false,
      // 存储当前编辑行的ID
      editRowId: '',
      dialogVisible: false,
      createForm: {
        name: '',
        methodCode: '',
        dictCode: '',
        certificationCriteria: '',
        sourceFileUrl: '',
        fieldCode: '',
        industryCode: ''
      },
      formRules: {
        methodCode: [
          { required: true, message: '请输入方法学编号', trigger: ['blur', 'change'] }
        ],
        dictCode: [
          { required: true, message: '请输入方法学字典码', trigger: ['blur', 'change'] }
        ],
        name: [
          { required: true, message: '请输入方法学名称', trigger: ['blur', 'change'] }
        ],
        fieldCode: [
          { required: true, message: '请选择领域', trigger: ['blur', 'change'] }
        ],
        certificationCriteria: [
          { required: true, message: '请选择核证标准', trigger: ['blur', 'change'] }
        ],
        sourceFileUrl: [
          { required: true, message: '请输入pdf文档url', trigger: ['blur', 'change'] },
          { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
        ]
      },
      statusCode: [],
      // 领域
      projectScope: [],
      // 资产类型
      assetType: [],
      // 项目类型
      projectType: [],
      // 交割方式列表
      deliveryMethod: [],
      // 交割场所列表
      deliveryExchange: [],

      // 核证机构
      certificationCriteria: [],
      // 交易状态
      transactionStatus: [],
      // 资产状态
      assetsStatus: [],
      // 产业类型
      industory: [],

      tableData: [],
      mainPageNum: 1,       // 主表格当前页码
      mainPageSize: 10,     // 主表格每页条数
      mainTotal: 0,         // 总记录数
      tableLoading: false,  // 表格加载状态
      methodUrl: "https://carbonmsger.feishu.cn/drive/folder/fldcn66yo6D4OoXwZqEMHL6OQSg?from=space_persnoal_filelist",
      user: JSON.parse(localStorage.getItem('user') || '{}'),

      form: {
        certificationCriteria: '', // 核证标准
        mName: '',          // 方法学（搜索用）
        projectScope: '',
        industry: '',
        statusCode: ''
      },
    };
  },

  computed: {
    // 计算总页数
    mainTotalPages() {
      if (this.mainTotal <= 0) return 0;
      return Math.ceil(this.mainTotal / this.mainPageSize);
    }
  },

  mounted() {
    this.queryMethods();
    this.loadSelectorData();
  },

  methods: {
    // 重置表单并关闭弹窗
    resetOfflineForm() {
      this.dialogVisible = false;
      
      // 延迟重置，确保弹窗关闭后再清空数据
      this.$nextTick(() => {
        this.isEditMode = false;
        this.editRowId = '';
        this.createForm = {
          name: '',
          methodCode: '',
          dictCode: '',
          certificationCriteria: '',
          sourceFileUrl: '',
          fieldCode: '',
          industryCode: ''
        };
        
        if (this.$refs.createFormRef) {
          this.$refs.createFormRef.resetFields();
        }
      });
    },

    // 提交表单
    handleSubmit() {
      this.$refs.createFormRef.validate((valid) => {
        if (valid) {
          // 提交前打印表单数据，用于调试
          console.log('提交的数据:', this.createForm);
          
          if (this.isEditMode) {
            this.$request({
              url: "/assets/carbonMethodology/update",
              method: "post",
              data: this.createForm
            }).then(res => {
              if (res.code === 200) {
                this.$message.success(res.msg);
                this.queryMethods();
                this.resetOfflineForm();
              }
            }).catch(error => {
              console.error('更新失败:', error);
              this.$message.error('更新失败，请重试');
            });
          } else {
            this.$request.post("/assets/carbonMethodology/upload", this.createForm)
              .then(res => {
                if (res.code === 200) {
                  this.$message.success(res.msg);
                  this.queryMethods();
                  this.resetOfflineForm();
                }
              })
              .catch(error => {
                console.error('新增失败:', error);
                this.$message.error('新增失败，请重试');
              });
          }
        }
      });
    },

    handleEdit(row) {
      // 1. 切换为编辑模式
      this.isEditMode = true;
      this.editRowId = row.id;
      
      // 深拷贝确保数据独立性
      this.createForm = {
        id: row.id,
        name: row.name || '', 
        methodCode: row.methodCode || '', 
        dictCode: row.dictCode || '', 
        certificationCriteria: row.certificationCriteria || '', 
        sourceFileUrl: row.sourceFileUrl || '', 
        fieldCode: row.fieldCode || '', 
        industryCode: row.industryCode || ''
      };
      
      this.dialogVisible = true;
      
      // 确保在DOM更新后清除验证
      this.$nextTick(() => {
        if (this.$refs.createFormRef) {
          this.$refs.createFormRef.clearValidate();
        }
      });
    },

    handleOnline(row) {
      this.$request.get("/assets/carbonMethodology/updateStatus", {
        params: { id: row.id }
      }).then(res => {
        if (res.code === 200) {
          this.$message.success(res.msg);
          this.queryMethods();
        }
      }).catch(error => {
        console.error('发布失败:', error);
        this.$message.error('发布失败，请重试');
      });
    },

    handleDownline(row) {
      this.$request.get("/assets/carbonMethodology/updateDownStatus", {
        params: { id: row.id }
      }).then(res => {
        if (res.code === 200) {
          this.$message.success(res.msg);
          this.queryMethods();
        }
      }).catch(error => {
        console.error('下线失败:', error);
        this.$message.error('下线失败，请重试');
      });
    },

    // 查询方法学列表
    queryMethods() {
      this.tableLoading = true;
      const params = {
        ...this.form,
        pageNum: this.mainPageNum,
        pageSize: this.mainPageSize
      };

      // 处理默认值为空的情况
      if (params.certificationCriteria === '0070000000') {
        params.certificationCriteria = null;
      }
      if (params.industry === '0020000000') {
        params.industry = null;
      }
      if (params.fieldCode === '0030000000') {
        params.fieldCode = null;
      }

      this.$request.get('/assets/carbonMethodology/sysQueryBySelector', {
        params: params
      }).then(res => {
        this.tableLoading = false;
        if (res.code === 200) {
          this.tableData = res.data.records || [];
          this.mainTotal = res.data.total || 0;
        }
      }).catch(error => {
        this.tableLoading = false;
        console.error("查询方法学列表失败:", error);
        this.$message.error('查询失败，请稍后重试');
      });
    },

    // 查看方法学文档
    handleView(url) {
      if (url) {
        window.open(url, '_blank');
      } else {
        this.$message.warning('没有可用的文档链接');
      }
    },

    handledelete(row) {
      console.log("删除id:", row.id);
      this.$request.delete("/assets/carbonMethodology/delete", {
        params: { id: row.id }
      }).then(res => {
        if (res.code === 200) {
          this.$message.success(res.msg);
          this.queryMethods();
        }
      }).catch(error => {
        console.error('删除失败:', error);
        this.$message.error('删除失败，请重试');
      });
    },

    // 加载筛选器数据
    loadSelectorData() {
      this.$request.get('/assets/carbonCreditAssets/querySelector').then(res => {
        if (res.code === 200) {
          this.certificationCriteria = res.data.certificationList || [];
          this.transactionStatus = res.data.transactionStatusList || [];
          this.assetsStatus = res.data.assetsStatusList || [];
          this.projectScope = res.data.projectScopeList || [];
          this.assetType = res.data.assetTypeList || [];
          this.projectType = res.data.projectTypeList || [];
          this.statusCode = res.data.statusCodeList || [];
          this.industory = res.data.industoryList || [];
        }
      }).catch(error => {
        console.error('加载筛选数据失败:', error);
        this.$message.error('加载筛选数据失败，请稍后重试');
      });
    },

    // 处理方法学搜索
    handleMethodSearch() {
      this.mainPageNum = 1;
      this.queryMethods();
    },

    // 重置主表格分页
    resetMainPagination() {
      this.mainPageNum = 1;
      this.queryMethods();
    },

    // 处理页码变化
    handleMainPageChange(val) {
      this.mainPageNum = val;
      this.queryMethods();
    },

    // 处理每页条数变化
    handleMainPageSizeChange(val) {
      this.mainPageSize = val;
      this.mainPageNum = 1;
      this.queryMethods();
    },

    // 处理选择变化
    handleSelectionChange(selection) {
      // 可以在这里处理表格选择逻辑
    }
  }
}
</script>

<style lang="scss" scoped>
.carbon-credit-page {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 64px);
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}

::v-deep .project-selector-table {
  border: none !important;
}

::v-deep .project-selector-table .el-table__header,
::v-deep .project-selector-table .el-table__body,
::v-deep .project-selector-table .el-table__row,
::v-deep .project-selector-table th,
::v-deep .project-selector-table td {
  border: none !important;
  border-collapse: collapse !important;
}

/* 顶部栏样式 */
.top-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #e6f7ed;
  padding: 10px 20px;
  border-radius: 4px;
  margin-bottom: 20px;

  .header-left {
    display: flex;
    align-items: center;

    .title {
      font-size: 16px;
      font-weight: bold;
      color: #52c41a;
      margin-left: 8px;
    }
  }

  .header-middle {
    color: #666;
    text-align: left;
    flex: 1;
    margin: 0 20px;
    font-size: 14px;

    .stat-item {
      margin-right: 10px;
    }

    .stat-value {
      color: #6cba12;
      font-weight: 700;
    }
  }

  .header-right {
    button {
      margin-left: 10px;
      &.el-button--primary {
        border-color: #409eff;
        color: #409eff;
      }
      &.el-button--success {
        border-color: #67c23a;
        color: #67c23a;
      }
    }
  }
}

/* 筛选区域样式 */
.filter-section {
  background: #f8f9fa;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;

  .filter-row,
  .search-row {
    display: flex;
    flex-wrap: wrap;
  }

  .filter-item {
    margin-bottom: 10px;
  }

  .filter-label {
    display: inline-block;
    font-size: 14px;
    color: #666;
    margin-bottom: 4px;
    min-width: 60px;
  }

  .filter-label2 {
    display: inline-block;
    font-size: 14px;
    color: #666;
    margin-bottom: 4px;
    width: 100px;
  }

  .filter-select,
  .filter-date {
    width: 100%;
    --el-input-border-color: #dcdfe6;
  }

  .search-container {
    display: flex;
    align-items: center;
    width: 100%;
  }

  .search-input {
    flex: 1;
    margin-right: 10px;
    --el-input-border-color: #dcdfe6;
  }
}

/* 操作按钮样式 */
.operation-btns {
  display: flex;
  gap: 10px;
  align-items: center;
  justify-content: center;

  .btn-text {
    cursor: pointer;
    color: #409eff;
    &.view {
      color: #409eff;
    }
    &.offline {
      color: #409eff;
    }
    &.inner {
      color: #67c23a;
    }
    &.modify {
      color: #f5a623;
    }
    &.delete {
      color: #f56c6c;
    }
    &:hover {
      text-decoration: underline;
    }
  }
}

/* 分页样式 */
.pagination {
  margin-top: 15px;
  text-align: right;
  padding: 10px 0;
}

/* 上传弹窗样式 */
.upload-dialog-content {
  padding: 20px 40px;
}

.form-row {
  margin-bottom: 5px;
}

.file-name {
  margin-top: 6px;
  color: #666;
  font-size: 12px;
  max-width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

::v-deep .el-form-item__label {
  font-weight: 1000;
}

::v-deep .el-upload__tip {
  margin-top: 5px !important;
}

/* 项目选择弹窗样式 */
.project-search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.project-pagination {
  text-align: right;
  margin-top: 15px;
}
</style>
